package cn.wolfcode.job;

import cn.wolfcode.domain.SeckillProductVo;
import cn.wolfcode.redis.SeckillRedisKey;
import cn.wolfcode.service.ISeckillProductService;
import com.alibaba.fastjson.JSON;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class SeckillProductJob {
    @Resource
    private ISeckillProductService seckillProductService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 秒杀商品及库存缓存到redis中，每天凌晨更新一次
     */
    @XxlJob("seckillProductCacheHandler")
    public void seckillProductCacheHandler() {
        System.out.println("定时上架功能");
        List<SeckillProductVo> seckillProductVos_10 = seckillProductService.queryByTime(10);
        syncToRedis(10, seckillProductVos_10);
        List<SeckillProductVo> seckillProductVos_12 = seckillProductService.queryByTime(12);
        syncToRedis(12, seckillProductVos_12);
        List<SeckillProductVo> seckillProductVos_14 = seckillProductService.queryByTime(14);
        syncToRedis(14, seckillProductVos_14);
        System.out.println("执行完成");
    }

    public void syncToRedis(Integer time, List<SeckillProductVo> lists) {
        String key = SeckillRedisKey.SECKILL_PRODUCT_HASH.getRealKey(time + "");
        String StockKey = SeckillRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(String.valueOf(time));
        //数据需要删除
        redisTemplate.delete(key);
        for (SeckillProductVo list : lists) {
            // 缓存商品
            redisTemplate.opsForHash().put(key, list.getId() + "", JSON.toJSONString(list));
            // 缓存库存
            redisTemplate.opsForHash().put(StockKey, list.getId() + "", list.getStockCount()+"");
        }

    }
}
